package me.sdevil507.platform.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.querydsl.jpa.impl.JPAQueryFactory;
import me.sdevil507.biz.fruit.dto.FruitParamsDTO;
import me.sdevil507.biz.fruit.mapper.FruitMapper;
import me.sdevil507.biz.fruit.po.QFruitOrgRelPo;
import me.sdevil507.biz.fruit.po.QFruitPO;
import me.sdevil507.biz.fruit.service.FruitService;
import me.sdevil507.org.dto.OrgDeptParamsDto;
import me.sdevil507.org.mapper.OrgDeptMapper;
import me.sdevil507.org.po.*;
import me.sdevil507.org.repository.OrgDeptRepository;
import me.sdevil507.org.repository.OrgExpertInfoRepository;
import me.sdevil507.org.repository.OrgUserRelRepository;
import me.sdevil507.org.repository.OrgUserRepository;
import me.sdevil507.org.service.OrgDeptService;
import me.sdevil507.org.service.OrgService;
import me.sdevil507.platform.service.PlatUtilService;
import me.sdevil507.supports.result.ApiResultDTO;
import me.sdevil507.supports.result.ApiResultGenerator;
import me.sdevil507.supports.status.ApiStatusCode;
import me.sdevil507.supports.status.ComConstant;
import me.sdevil507.supports.thread.ExecutorConfig;
import me.sdevil507.supports.util.CommonUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class PlatUtilServiceImpl implements PlatUtilService {

    @Autowired
    JPAQueryFactory jpaQueryFactory;

    @Autowired
    OrgService orgService;

    @Autowired
    OrgDeptService orgDeptService;

    @Autowired
    FruitService fruitService;

    @Autowired
    FruitMapper fruitMapper;

    @Autowired
    OrgDeptMapper orgDeptMapper;

    @Autowired
    OrgDeptRepository orgDeptRepository;

    @Autowired
    OrgUserRepository orgUserRepository;

    @Autowired
    OrgUserRelRepository orgUserRelRepository;

    @Autowired
    OrgExpertInfoRepository orgExpertInfoRepository;

    @Autowired
    private ExecutorConfig executorConfig;

    @Override
    public void dealDeptUser() {
        //获取所有是智库的部门信息
        QOrgDeptPo qOrgDeptPo = QOrgDeptPo.orgDeptPo;
        List<OrgDeptPo> deptPos = jpaQueryFactory.selectFrom(qOrgDeptPo).where(qOrgDeptPo.itIsOrg.isTrue().and(qOrgDeptPo.itIsRoot.isTrue())).fetch();
        System.out.println("--------查找到部门是机构性质的有----"+ deptPos.size() + "---个-------");
        this.setOrgUserRel(deptPos);
    }

    public void setOrgUserRel(List<OrgDeptPo> deptPos){
        //查找部门下的人员是否都已经在orgUserRel存在
        deptPos.forEach(orgDeptPo -> {
            //获取当前节点下面的用户
            List<OrgUserPo> orgUserList = orgDeptPo.getUsers();
            Long orgId = orgDeptPo.getOrg().getId();
            //查询orgUserRel
            QOrgUserRelPo qOrgUserRelPo = QOrgUserRelPo.orgUserRelPo;
            orgUserList.forEach(orgUserPo -> {
                long count = jpaQueryFactory.selectFrom(qOrgUserRelPo).where(qOrgUserRelPo.user.id.eq(orgUserPo.getId()).and(qOrgUserRelPo.org.id.eq(orgId))).fetchCount();
                if(count == 0){
                    System.out.println("--------查找到用户----"+ orgUserPo.getRealName() + "---不在机构" + orgDeptPo.getOrg().getShortNameZh() + "---关联关系下-------");
                    //与机构关联信息
                    OrgUserRelPo orgUserRelPo = new OrgUserRelPo();
                    orgUserRelPo.setOrg(orgDeptPo);
                    orgUserRelPo.setUser(orgUserPo);
                    orgUserRelPo.setExpert(false);
                    orgUserRelPo.setMgr(true);
                    orgUserRelRepository.save(orgUserRelPo);
                    System.out.println("--------用户----"+ orgUserPo.getRealName() + "---在机构" + orgDeptPo.getOrg().getShortNameZh() + "---关联关系处理成功-------");
                }
            });

            if(!CollectionUtils.isEmpty(orgDeptPo.getChildren())){
                //递归
                this.setOrgUserRel(orgDeptPo.getChildren());
            }
        });
    }


    /**
     * 序号	姓名	所属单位	所属部门	职务	备注
     * @param file
     * @return
     */
    @Override
    public ApiResultDTO importOrgManager(File file) {
        ApiResultDTO apiResultDTO;
        Workbook workbook = null;
        StringBuilder message = new StringBuilder();
        try {
            if (file.getPath().endsWith("xls")) {
                workbook = new HSSFWorkbook(new FileInputStream(file));
            } else if (file.getPath().endsWith("xlsx")) {
                workbook = new XSSFWorkbook(new FileInputStream(file));
            }
            int sheetNum = workbook.getNumberOfSheets();
            for (int i = 0; i < sheetNum; i++) {
                Sheet sheet = workbook.getSheetAt(i);
                String orgName = sheet.getSheetName();

//                OrgPo orgPO = orgService.getOrgInfoByOrgName(orgName);
                OrgDeptPo orgDeptPo = orgDeptService.getByOrgName(orgName);
                OrgUserRelPo orgUserRelNewPo = new OrgUserRelPo();
                if(orgDeptPo == null){
                    message.append("第").append(i+1).append("个sheet的机构名称查不到");
                }else{
                    System.out.println("开始处理第" + (i+1) + "个sheet，名称===" + orgName);

                    // 获取每行中的字段,过滤首行说明和第二行字段信息
                    for (int m = 1; m <= sheet.getLastRowNum(); m++) {
                        Row row = sheet.getRow(m);
                        Cell cellName = row.getCell(1);
                        //姓名
                        OrgUserPo orgUserPo = null;
                        if (null == cellName || CellType.BLANK.getCode() == cellName.getCellType()) {
                            message.append("第").append(i + 1).append("行的姓名不能为空;\n");
                        }else{
                            String userName = CommonUtil.replaceBlank(row.getCell(1).toString());
                            for (OrgUserPo user : orgDeptPo.getUsers()) {
                                if(user.getRealName().equals(userName) ){
                                    orgUserPo = user;
                                    break;
                                }
                            }
                            if(orgUserPo == null){
                                orgUserPo = new OrgUserPo();
                                orgUserPo.setRealName(userName);
                                orgUserPo.setPassword("e10adc3949ba59abbe56e057f20f883e");

                                orgUserRelNewPo.setFullTime(false);
                                orgUserRelNewPo.setExpert(false);
                                orgUserRelNewPo.setMgr(true);
                                orgUserRelNewPo.setOrg(orgDeptPo);
                                orgUserRelNewPo.setUser(orgUserPo);

                                orgUserRelRepository.save(orgUserRelNewPo);
                            }

                            //所属单位
                            Cell cellUnit = row.getCell(2);
                            if (null != cellUnit || CellType.BLANK.getCode() != cellUnit.getCellType()) {
                                orgUserPo.setUnit(cellUnit.getStringCellValue());
                            }
                            //职务
                            Cell cellJobTitle = row.getCell(4);
                            if (cellJobTitle != null && CellType.BLANK.getCode() != cellUnit.getCellType()) {
                                orgUserPo.setJobTitle(cellJobTitle.getStringCellValue());
                            }
                            //备注
                            Cell cellSummary = row.getCell(5);
                            if (cellSummary != null && CellType.BLANK.getCode() != cellUnit.getCellType()) {
                                orgUserPo.setSummary(cellSummary.getStringCellValue());
                            }

                            OrgUserPo newUser = orgUserRepository.save(orgUserPo);

                            //所属部门
//                            Cell cellDept = row.getCell(3);
//                            OrgDeptPo rootOrgDeptPo = orgDeptService.getByOrgId(orgPO.getId());
//                            if (CellType.BLANK.getCode() != cellUnit.getCellType()) {
//                                String deptName = cellDept.toString();
//                                //确定部门是否已经存在
//                                List<OrgDeptPo> depts = orgPO.getDepts().stream().filter(orgDeptPo -> orgDeptPo.getTitle().equals(deptName) && !orgDeptPo.isDeleted()).collect(Collectors.toList());
//                                if(!CollectionUtils.isEmpty(depts)){
//                                    newUser.setDepts(depts);
//                                }else{
//                                    //新建部门
//                                    OrgDeptParamsDto orgDeptParamsDto = new OrgDeptParamsDto();
//                                    orgDeptParamsDto.setTitle(deptName);
//                                    orgDeptParamsDto.setOrgId(orgPO.getId());
//                                    orgDeptParamsDto.setItIsOrg(true);
//                                    orgDeptParamsDto.setParentId(rootOrgDeptPo.getId());
//                                    OrgDeptPo newDeptPo = orgDeptMapper.dto2po(orgDeptParamsDto);
//                                    orgDeptRepository.save(newDeptPo);
//
//                                    List<OrgDeptPo> newDepts = new ArrayList<>();
//                                    newDepts.add(newDeptPo);
//
//                                    if(!CollectionUtils.isEmpty(newUser.getDepts())){
//                                        newUser.getDepts().clear();
//                                    }
//                                    newUser.setDepts(newDepts);
//
//                                    orgPO.getDepts().add(newDeptPo);
//                                }
//                            }else{
//                                //挂在根部门下面
//                                List<OrgDeptPo> tempDepts = new ArrayList<>();
//                                tempDepts.add(rootOrgDeptPo);
//                                newUser.setDepts(tempDepts);
//                            }
                            orgUserRepository.save(newUser);

                            System.out.println("第" + (i+1) + "个sheet，名称===" + orgUserPo.getRealName() + "===处理成功!");
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            apiResultDTO = ApiResultGenerator.create("-1", "导入数据失败！");
            return apiResultDTO;
        }
        if (message.length() == 0) {
            apiResultDTO = ApiResultGenerator.create(ApiStatusCode.SUCCESS.getCode(), "导入数据成功");
        } else {
            apiResultDTO = ApiResultGenerator.create("-1", message.toString());
        }
        return apiResultDTO;
    }

    @Override
    public ApiResultDTO dealOrgExpert(File file) {

        ApiResultDTO apiResultDTO;
        Workbook workbook = null;
        StringBuilder message = new StringBuilder();
        try {
            if (file.getPath().endsWith("xls")) {
                workbook = new HSSFWorkbook(new FileInputStream(file));
            } else if (file.getPath().endsWith("xlsx")) {
                workbook = new XSSFWorkbook(new FileInputStream(file));
            }
            int sheetNum = workbook.getNumberOfSheets();
            QOrgUserPo qOrgUserPo = QOrgUserPo.orgUserPo;
            QTempExpertPo qTempExpertPo = QTempExpertPo.tempExpertPo;
            QOrgUserRelPo qOrgUserRelPo = QOrgUserRelPo.orgUserRelPo;
            for (int i = 0; i < sheetNum; i++) {
                Sheet sheet = workbook.getSheetAt(i);
                String orgName = sheet.getSheetName();

//                OrgPo orgPO = orgService.getOrgInfoByOrgName(orgName);
                OrgDeptPo orgDeptPo = orgDeptService.getByOrgName(orgName);
                if(orgDeptPo == null){
                    message.append("第").append(i+1).append("个sheet的机构名称查不到");
                }else{
                    System.out.println("开始处理第" + (i+1) + "个sheet，名称===============" + orgName + "===============");

                    // 获取每行中的字段,过滤首行说明和第二行字段信息
                    for (int m = 1; m <= sheet.getLastRowNum(); m++) {
                        Row row = sheet.getRow(m);
                        if (row == null || row.toString().isEmpty()) {
                            break;
                        }
                        //姓名
                        Cell cellName = row.getCell(1);
                        String name = "";
                        if (null != cellName || CellType.BLANK.getCode() != cellName.getCellType()) {
                            name = CommonUtil.replaceBlank(cellName.getStringCellValue());
                        }
                        System.out.println("----共获取到"+sheet.getLastRowNum()+"个专家，开始处理第"+m+"个专家-----" + name + "---------");
                        //所属单位
                        Cell cellCompany = row.getCell(2);
                        String company = "";
                        if (null != cellCompany || CellType.BLANK.getCode() != cellCompany.getCellType()) {
                            company = cellCompany.getStringCellValue();
                        }
                        //职务
                        Cell cellPosition = row.getCell(3);
                        String position = "";
                        if (null != cellPosition && CellType.BLANK.getCode() != cellPosition.getCellType()) {
                            position = cellPosition.getStringCellValue();
                        }
                        //职称
                        Cell cellTheTitle = row.getCell(4);
                        String theTitle = "";
                        if (null != cellTheTitle && CellType.BLANK.getCode() != cellTheTitle.getCellType()) {
                            theTitle = cellTheTitle.getStringCellValue();
                        }
                        //学历
                        Cell cellEducation = row.getCell(5);
                        String education = "";
                        if (null != cellEducation && CellType.BLANK.getCode() != cellEducation.getCellType()) {
                            education = cellEducation.getStringCellValue();
                        }
                        //研究方向
                        Cell cellResearchDomain = row.getCell(6);
                        String researchDomain = "";
                        if (null != cellResearchDomain && CellType.BLANK.getCode() != cellResearchDomain.getCellType()) {
                            researchDomain = cellResearchDomain.getStringCellValue();
                        }
                        //学术头衔
                        Cell cellAcademicTitle = row.getCell(7);
                        String academicTitle = "";
                        if (null != cellAcademicTitle && CellType.BLANK.getCode() != cellAcademicTitle.getCellType()) {
                            academicTitle = cellAcademicTitle.getStringCellValue();
                        }
                        //行政级别
                        Cell cellTitleLevel = row.getCell(8);
                        String titleLevel = "";
                        if (null != cellTitleLevel && CellType.BLANK.getCode() != cellTitleLevel.getCellType()) {
                            titleLevel = cellTitleLevel.getStringCellValue();
                        }
                        //全职/兼职
                        Cell cellFullTime = row.getCell(9);
                        boolean fullTime = false;
                        if (null != cellFullTime && CellType.BLANK.getCode() != cellFullTime.getCellType()) {
                            fullTime = ("全职").equals(cellFullTime.getStringCellValue());
                        }
                        //备注
                        Cell cellSummary = row.getCell(10);
                        String summary = "";
                        if (cellSummary != null && CellType.BLANK.getCode() != cellSummary.getCellType()) {
                            summary = cellSummary.getStringCellValue();
                        }

                        //查询正式专家信息
//                        OrgUserPo orgUserPo = orgUserRepository.findByRealNameAndExpertInfoIsNotNullAndDeletedIsFalse(name);
                        OrgUserPo orgUserPo = jpaQueryFactory.select(qOrgUserPo)
                                .from(qOrgUserRelPo)
                                .leftJoin(qOrgUserPo).on(qOrgUserRelPo.user.id.eq(qOrgUserPo.id))
                                .where(qOrgUserRelPo.org.id.eq(orgDeptPo.getId())
                                        .and(qOrgUserPo.realName.eq(name))
                                        .and(qOrgUserPo.expertInfo.isNotNull())
                                        .and(qOrgUserPo.deleted.isFalse())
                                ).fetchOne();

                        OrgExpertInfoPo orgExpertInfoPo = new OrgExpertInfoPo();
                        if(orgUserPo != null) {
                            orgExpertInfoPo = orgUserPo.getExpertInfo();
                        }
                        orgExpertInfoPo.setCompany(company);
                        orgExpertInfoPo.setPosition(position);
                        orgExpertInfoPo.setTheTitle(theTitle);
                        orgExpertInfoPo.setEducation(education);
                        orgExpertInfoPo.setResearchDomain(researchDomain);
                        orgExpertInfoPo.setAcademicTitle(academicTitle);
                        orgExpertInfoPo.setTitleLevel(titleLevel);
                        orgExpertInfoRepository.save(orgExpertInfoPo);

                        if(orgUserPo != null){
                            //查询与机构对应关系
//                            List<OrgUserRelPo> ourps = orgUserPo.getOrgUserRel().stream()
//                                    .filter(our->
//                                            our.getOrg() != null
//                                            && orgPO.getId().equals(
//                                                    our.getOrg().getId()
//                                            )
//                                    ).collect(Collectors.toList());

                            List<OrgUserRelPo> ourps = jpaQueryFactory.selectFrom(qOrgUserRelPo).where(qOrgUserRelPo.org.id.eq(orgDeptPo.getId())).fetch();
                            //如果没有对应关系--新增
                            if(CollectionUtils.isEmpty(ourps)){
                                OrgUserRelPo orgUserRelPo = new OrgUserRelPo();
                                orgUserRelPo.setOrg(orgDeptPo);
                                orgUserRelPo.setUser(orgUserPo);
                                orgUserRelPo.setExpert(true);
                                orgUserRelPo.setFullTime(fullTime);
                                orgUserRelRepository.save(orgUserRelPo);
                            }
                            System.out.println("----查询到正式专家信息----"+ name + "---------");
                        }else{
                            //查询临时专家信息
//                            try {
//                                TempExpertPo tempExpertPo = jpaQueryFactory.selectFrom(qTempExpertPo)
//                                        .where(qTempExpertPo.orgID.eq(orgPO.getId())
//                                                .and(qTempExpertPo.realName.eq(name))
//                                                .and(qTempExpertPo.deleted.isFalse())
//                                        ).fetchOne();
//                            } catch (NonUniqueResultException e) {
//                                e.printStackTrace();
//                                System.out.println("----查询到---"+orgPO.getShortNameZh()+"的临时专家信息----"+ name + "---出现多个------");
//                            }

                            //用户信息
                            orgUserPo = new OrgUserPo();
                            orgUserPo.setRealName(name);
                            orgUserPo.setPassword("e10adc3949ba59abbe56e057f20f883e");
                            orgUserPo.setSummary(summary);
                            orgUserPo.setUnit(company);
                            orgUserPo.setJobTitle(position);
                            orgUserPo.setExpertInfo(orgExpertInfoPo);
                            orgUserRepository.save(orgUserPo);

                            //与机构关联信息
                            OrgUserRelPo orgUserRelPo = new OrgUserRelPo();
                            orgUserRelPo.setOrg(orgDeptPo);
                            orgUserRelPo.setUser(orgUserPo);
                            orgUserRelPo.setExpert(true);
                            orgUserRelPo.setFullTime(fullTime);
                            orgUserRelRepository.save(orgUserRelPo);
                        }
                        System.out.println("---------第"+m+"个--专家-----" + name + "------处理完毕-----------");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            apiResultDTO = ApiResultGenerator.create("-1", "导入数据失败！");
            return apiResultDTO;
        }
        if (message.length() == 0) {
            apiResultDTO = ApiResultGenerator.create(ApiStatusCode.SUCCESS.getCode(), "导入数据成功");
        } else {
            apiResultDTO = ApiResultGenerator.create("-1", message.toString());
        }
        return apiResultDTO;
    }

    @Override
    public ApiResultDTO dealOrgFruit(File tempFile) {
        return null;
    }


    @Override
    public void dealFruitKeyWord(FruitParamsDTO fruitParamsDTO) {

        QFruitPO qFruitPO = QFruitPO.fruitPO;
        QFruitOrgRelPo qFruitOrgRelPo = QFruitOrgRelPo.fruitOrgRelPo;
    }
}